package it.koutifaris.travianmap.dal.sqlservices;

import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Revisions.COLUMN_NAME_DATE;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Revisions.COLUMN_NAME_REVISION_ID;
import static it.koutifaris.travianmap.dal.sqlservices.MapSqlContract.Revisions.TABLE_NAME;

import java.util.Calendar;
import java.util.Date;

import junit.framework.Assert;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;

public class RevisionsTableTest extends AbstractMapDbTest {

	private final String[] COLUMNS = { COLUMN_NAME_REVISION_ID, COLUMN_NAME_DATE };

	public void testRevisionsTableExist() {
		getDbHelper().getReadableDatabase().rawQuery("select 1 from " + TABLE_NAME, null);
	}

	public void testRevisionsTablePK() {
		ContentValues contentValues = new ContentValues();

		Date today = truncDateToDay(new Date());
		setRevisionData(contentValues, today);

		getDbHelper().getWritableDatabase().insertOrThrow(TABLE_NAME, null, contentValues);
		try {
			getDbHelper().getWritableDatabase().insertOrThrow(TABLE_NAME, null, contentValues);
			Assert.fail("PK must be unique");
		} catch (SQLException e) {
			// OK, test passed
		}

	}

	public void testRevisionsTableInsert() {
		ContentValues contentValues = new ContentValues();

		Date today = truncDateToDay(new Date());
		setRevisionData(contentValues, today);

		getDbHelper().getWritableDatabase().insert(TABLE_NAME, null, contentValues);

		Cursor cursor = getDbHelper().getReadableDatabase().query(TABLE_NAME, COLUMNS, null, null, null, null, null);

		cursor.moveToNext();
		Assert.assertEquals(1, cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_REVISION_ID)));
		Assert.assertEquals(today, new Date(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_DATE))));
	}

	private void setRevisionData(ContentValues contentValues, Date today) {
		contentValues.put(COLUMN_NAME_REVISION_ID, 1);
		contentValues.put(COLUMN_NAME_DATE, today.getTime());
	}

	private Date truncDateToDay(Date date) {
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.HOUR_OF_DAY, 0);
		cal.set(Calendar.MINUTE, 0);
		cal.set(Calendar.SECOND, 0);
		cal.set(Calendar.MILLISECOND, 0);

		return cal.getTime();
	}

}
